import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/15
 * Time: 21:37
 */
public class Solution {
//    public int totalFruit(int[] fruits) {
//        if(fruits.length < 3) return fruits.length;
//        HashMap<Integer,Integer> map = new HashMap<>();
//        int count = Integer.MIN_VALUE,left = 0,right = 0;
//        while(right < fruits.length){
//            //如果key = fruits[right]存在,则value在原基础上 + 1,否则默认为0 + 1
//            map.put(fruits[right],map.getOrDefault(fruits[right],0)+1);//进窗口
//            while (map.size() > 2){
//                //将key = fruits[left]的value - 1
//                map.put(fruits[left],map.get(fruits[left])-1);//出窗口
//                //如果value = 0,则将该元素从哈希表中移除
//                if(map.get(fruits[left]) == 0){
//                    map.remove(fruits[left]);
//                }
//                left++;
//            }
//            count = Math.max(count,right - left + 1);
//            right++;
//        }
//        return count;
//    }
    public int totalFruit(int[] fruits) {
        if(fruits.length < 3) return fruits.length;
        int[] hash = new int[fruits.length + 1];
        int kinds = 0,left = 0,right = 0,count = Integer.MIN_VALUE;
        while(right < fruits.length){
            if(hash[fruits[right]] == 0){
                kinds++;
            }
            hash[fruits[right]]++;//进窗口
            while (kinds > 2){
                hash[fruits[left]]--;//出窗口
                if(hash[fruits[left]] == 0){
                    kinds--;
                }
                left++;
            }
            count = Math.max(count,right - left + 1);
            right++;
        }
        return count;
    }
    public static void main(String[] args) {
        Solution s = new Solution();
        int ret = s.totalFruit(new int[]{0, 1, 2, 2});
        System.out.println(ret);
    }
}